package ru.ifmo.itmokis.sim;

import java.util.ArrayList;
import java.util.List;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import ru.ifmo.itmokis.domain.Order.Status;
import ru.ifmo.itmokis.domain.Time;
import ru.ifmo.itmokis.util.DataContext;
import ru.ifmo.itmokis.util.EventDriven;

/**
 *
 * @author ivan
 */
public class Statistics implements ClockListener, EventDriven {

    public static final Time PERIOD = new Time(3, 0);
    private DataContext dataContext;
    // ^ Dependencies ^
    private Time nextEventTime = Time.ZERO;
    private List<Integer[]> orderStats = new ArrayList<Integer[]>();
    private XYSeries app = new XYSeries("approved");
    private XYSeries pro = new XYSeries("inprogress");
    private XYSeries cmp = new XYSeries("completed");

    public Statistics(DataContext dataContext) {
        this.dataContext = dataContext;
    }

    public XYSeriesCollection getDataset() {
        XYSeriesCollection ret = new XYSeriesCollection();
        ret.addSeries(app);
        ret.addSeries(pro);
        ret.addSeries(cmp);
        return ret;
    }

    @Override
    public void process(Time time) {
        if (time.equals(nextEventTime)) {
            // Collect statistics
            int a = dataContext.countOrdersByStatus(Status.APPROVED);
            int p = dataContext.countOrdersByStatus(Status.IN_PROGRESS);
            int c = dataContext.countOrdersByStatus(Status.COMPLETED);

            app.add(time.toPlainHours(), a);
            pro.add(time.toPlainHours(), p);
            cmp.add(time.toPlainHours(), c);

            scheduleEvent(nextEventTime.add(PERIOD));
        }
    }

    @Override
    public void scheduleEvent(Time time) {
        nextEventTime = time;
    }
}
